package com.Hermes.NSP;

import com.Hermes.Omega.PK;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.ElementPowPreProcessing;
import it.unisa.dia.gas.jpbc.PairingPreProcessing;

import java.math.BigInteger;
import java.security.SecureRandom;

public class EncVecPreProcessingTools {
    private final PairingPreProcessing ppp0;
    private final PairingPreProcessing ppp1;


    private final ElementPowPreProcessing h1;

    public EncVecPreProcessingTools(EncVec esd, PK _pk) {
        Element ex = esd.getEvec()[0].getImmutable();
        Element ey = esd.getEvec()[1].getImmutable();
        ppp0 = _pk.getE().getPairingPreProcessingFromElement(ex);
        ppp1 = _pk.getE().getPairingPreProcessingFromElement(ey);
        h1 = _pk.getH1().getElementPowPreProcessing();


    }

//    private

    public Element ENCS_SD_SP(EncVec esp) {
        Element first = ppp0.pairing(esp.getEvec()[0]).getImmutable();//初始化为类的全局变量
        Element second = ppp1.pairing(esp.getEvec()[1]).getImmutable();
//        Element h1 = pk.getH1().getImmutable();//可以加速
        byte[] r2b = new byte[32], r3b = new byte[32];
        SecureRandom rng = new SecureRandom(r2b);
        rng.nextBytes(r2b);
        rng.nextBytes(r3b);
        BigInteger r2 = new BigInteger(r2b), r3 = new BigInteger(r3b);
        Element h2 = h1.pow(r2).getImmutable(), h3 = h1.pow(r3).getImmutable();
        Element gh1 = first.mul(h2).getImmutable();
        Element gh2 = second.mul(h3).getImmutable();
        Element res = gh1.mul(gh2).getImmutable();
        return res.getImmutable();
    }


    public Element Enum_P1P2_SD(EncNode p1, EncNode p2) {
        EncVec ep2p1 = new EncVec(p2, p1);
        Element first = ppp0.pairing(ep2p1.getEvec()[0]).getImmutable();
        Element second = ppp1.pairing(ep2p1.getEvec()[1]).getImmutable();
//        Element h1 = pk.getH1().getImmutable();
        byte[] r2b = new byte[32], r3b = new byte[32];
        SecureRandom rng = new SecureRandom(r2b);
        rng.nextBytes(r2b);
        rng.nextBytes(r3b);
        BigInteger r2 = new BigInteger(r2b), r3 = new BigInteger(r3b);
        Element h2 = h1.pow(r2).getImmutable(), h3 = h1.pow(r3).getImmutable();
        Element gh1 = first.mul(h2).getImmutable();
        Element gh2 = second.mul(h3).getImmutable();
        Element res = gh1.mul(gh2).getImmutable();
        return res.getImmutable();
    }


}
